package com.mallcai.bigdata.ladon.service.report.impl;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.mallcai.bigdata.ladon.service.report.IMetaRefreshService;
import com.mallcai.bigdata.ladon.service.report.IReportObjectQueryService;
import com.mallcai.bigdata.ladon.service.report.IReportQueryStatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-09-05 15:32
 */
@Slf4j
@Service
public class MetaRefreshService implements IMetaRefreshService {

    private EventBus eventBus;

    @Autowired
    private IReportObjectQueryService iReportObjectQueryService;

    @Autowired
    private IReportQueryStatisticService iReportQueryStatisticService;

    @PostConstruct
    private void init(){
        ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(1000),
                new ThreadFactoryBuilder().setNameFormat("metaRefresh%d").setDaemon(true).build());
        eventBus =  new AsyncEventBus("metaRefresh", executorService);
        eventBus.register(this);
    }

    @Subscribe
    private void listen(MetaRefreshEvent metaRefreshEvent){
        log.info("MetaRefreshEventListener接收到新事件:{}", metaRefreshEvent);
        iReportObjectQueryService.evictMetaCache(metaRefreshEvent);
        if(metaRefreshEvent.getType().equalsIgnoreCase(MetaRefreshType.REPORT.getCode())){
            iReportQueryStatisticService.resetErrorCall(metaRefreshEvent.getKey());
        }
    }


    @Override
    public void publishEvent(MetaRefreshEvent metaRefreshEvent){
        eventBus.post(metaRefreshEvent);
    }

}
